package com.hundredapp.oa.util;

import java.util.List;
import java.util.Map;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import com.hundredapp.oa.repository.UserManager;
import com.hundredapp.oa.vo.ServiceVO;
import com.opensymphony.xwork2.ActionContext;

public class DaoAspect {
	
	@Autowired
	private UserManager usermanager;
	
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		Object retVal;
		Object[] args=pjp.getArgs();
		int length=args.length;
		Object[] newArgs=new Object[length];
		Map<String, Object> session_map=ActionContext.getContext().getSession();
		if(session_map.get("lgoin_user_id")!=null){
			int id=Integer.parseInt(session_map.get("lgoin_user_id").toString());
			List<ServiceVO> services=usermanager.findService(id);
			if(length>0){
				boolean flag=false;
				for(ServiceVO serv:services){
					if(classNameToActionName(pjp.getTarget().getClass().getName()).startsWith(serv.getManagerName())&&
							serv.getPermission()==2){
						flag=true;
					}
				}
				if(flag){
					return pjp.proceed();
				}else{
					String arg=args[0]+" and create_user_id="+id;
					newArgs[0]=arg;
					if(length>1){
						for(int i=1;i<length;i++){
							newArgs[i]=args[i];
						}
					}
					return pjp.proceed(newArgs);
				}
			}
		}
		retVal=pjp.proceed();
		return retVal;
	}
	
	private String classNameToActionName(String className){
		String[] split=className.split("\\.");
		String actionName=split[split.length-1];
		return actionName;
	}

	public void setUsermanager(UserManager usermanager) {
		this.usermanager = usermanager;
	}
}
